using System;
using System.Collections.Generic;

using log4net;

using GymManager.Exception;
using GymManager.Persistence.DAO;
using GymManager.Persistence.VO;

namespace GymManager.Business
{
    /// <summary>
    /// Class responsible by providing services regarding access control
    /// </summary>
    public class AccessControlServices
    {
        // logger instance
        private ILog _logManager = LogManager.GetLogger(typeof(AccessControlServices));

        /// <summary>
        /// Method responsible by checking if a function can be accessed by an specific user role
        /// </summary>
        /// <param name="String">some string representing a key for a feature</param>
        /// <param name="Role">role which is trying to acess the given feature</param>
        /// <returns>Boolean - flag indicating if the a given user has access to an specific function</returns>
        /// <see cref="GymManager.Exception.BusinessException"/>
        public Boolean isFeatureCanBeAccessed(String featureKey, Role userRole)
        {
            if (_logManager.IsInfoEnabled)
            {
                _logManager.Info("Begin Method");
            }

            Boolean isFeatureCanBeAccessed = false;

            try
            {
                // permission list
                IList<Permission> permissionList = null;

                // building value object to be used as filter
                Permission permissionFilterVO = new Permission();
                permissionFilterVO.FeatureKey = featureKey;
                permissionFilterVO.RoleId = userRole.Id;

                // getting information about the relationship between features and roles
                PermissionDAO permissionDAO = new PermissionDAO();
                permissionList = permissionDAO.findByAny(permissionFilterVO);                

                // if the permission list is not empty, so the user has access to the given feature
                isFeatureCanBeAccessed = (permissionList != null && permissionList.Count > 0);
            }
            catch (PersistenceException)
            {
                throw new BusinessException();
            }            
            
            if (_logManager.IsInfoEnabled)
            {
                _logManager.Info("End Method");
            }

            return isFeatureCanBeAccessed;
        }
    }
}
